package gotnames.web.st;

import gotnames.Utils;
import gotnames.dm.Group;
import gotnames.dm.KTrans;
import gotnames.dm.User;
import gotnames.dm.User.Gender;
import gotnames.web.GotNamesServlet.UserAuthenticator;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.medallia.spider.DropdownElement;
import com.medallia.spider.RenderTask;

/**
 * Task which both renders and receives the form used to create a new group. A
 * user gets here by clicking on the link in the email they got from
 * {@link RegisterTask}.
 */
public class CreateGroupTask extends RenderTask {
	
	@Input interface Params {
		String auth();
		String name();
		
		String email();
		String firstName();
		String lastName();
		Gender gender();
	}
	
	@Output interface Values {
		V<List<DropdownElement>> GENDER_OPTIONS = v();
		V<String> EMAIL = v();
		V<String> TOKEN = v();
	}
	
	PostAction action(final Params p, UserAuthenticator userAuthenticator, PersistenceManager pm) {
		final String email = p.email();
		String token = p.auth();
		
		if (email == null || token == null || !token.equals(RegisterTask.makeEmailToken(email)))
			return rawStringUtf8("Invalid token");
		
		final String name = p.name();
		if (name != null) {
			// create the group
			final Group g = new KTrans<Group>(pm) {
				@Override protected Group call() {
					Group g = new Group();
					g.setName(name);
					
					pm.makePersistent(g);
					
					return g;
				}
			}.go();
			
			// create first admin user
			String authToken = new KTrans<String>(pm) {
				@Override protected String call() {
					User u = User.newUser(g.getKey());
					
					u.setEmail(email);
					u.setFirstName(Utils.notNull(p.firstName(), "First name is required"));
					u.setLastName(Utils.notNull(p.lastName(), "Last name is required"));
					u.setGender(Utils.notNull(p.gender(), "Gender is required"));
					
					u.setAdmin(true);
					
					pm.makePersistent(u);
					
					return u.getAuthToken();
				}
			}.go();
			
			// authenticate admin user
			userAuthenticator.authenticate(authToken);
			
			return redirectToTask(AdminTask.class);
		} else {
			// render form
			attr(Values.GENDER_OPTIONS, DropdownElement.fromEnum(Gender.class, null));
			attr(Values.EMAIL, email);
			attr(Values.TOKEN, token);
			return null;
		}
	}

	@Override public String getPageTitle() { return "Create Group"; }

}
